# -*- coding: UTF-8 -*-

# Copyright (c) 2007 Daniele Favara <nomed@dsslive.org>.
#
# This is free software you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, or (at your option) any
# later version.
#
# This software is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software; see the file COPYING.  If not, write to the Free
# Software Foundation, Inc., 51 Franilin St, Fifth Floor, Boston, MA


from turbogears import expose, flash, url
from tginvoice.controllers import ControllerObj

from turbogears import identity, redirect
from cherrypy import request, response

from tginvoice.model import tables, database
from tginvoice.utils import standard, form
from formencode import Invalid
import logging
log = logging.getLogger("tginvoice.controllers.customer")

class Customers(ControllerObj):

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.customers")
    def index(self, *args, **kw):
        return dict(this=self,
                    release = self.release,
                    customers=self.pcustomers,
                    mapper_customer=self.mapper_customer,
                    iterator_customer=self.iterator_customer)


    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.customers_show")
    def show(self, id=None, *args, **kw):
        customer = self._get_customer(id)

        if not self.check_identity_user(customer):
            return None

        return dict(this=self,
                    customer= customer,
                    )

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.customers_new")
    def new(self, *args, **kw):
        new_customer = {}
        errors = {}
        if kw.has_key('errors'):
            errors = kw['errors']
        if kw.has_key('new_customer'):
            new_customer = kw['new_customer']
        for col in self.iterator_customer_editable:
            if not new_customer.has_key(col):
                new_customer[col] = ''
        if kw.has_key('actions'):
            if kw['actions'].has_key('save'):
                validate = form.Customer()
                try:
                    data = validate.to_python(kw['new_customer'])
                    tables.session.begin()
                    customer_obj = tables.Customer()
                    for val in self.iterator_customer_editable:
                        setattr(customer_obj, val, data[val])
                    if self.puser:
                        self.puser.customer.append(customer_obj)
                    tables.session.commit()
                    raise redirect(url('.'))
                except Invalid, e:
                    errors = e.unpack_errors()

        return dict(this=self,
                    errors = errors,
                    new_customer = new_customer,
                    release = self.release,
                    mapper_customer=self.mapper_customer,
                    iterator_customer_editable=self.iterator_customer_editable
                    )

    @identity.require(identity.not_anonymous())
    @expose(template="tginvoice.templates.customers_edit")
    def edit(self, id=None, *args, **kw):
        customer_obj = self._get_customer(id=id)

        if not self.check_identity_user(customer_obj):
            return None

        edit_customer = {}
        errors = {}
        if kw.has_key('errors'):
            errors = kw['errors']
        if kw.has_key('edit_customer'):
            edit_customer = kw['edit_customer']
        for col in self.iterator_customer_editable:
            if not edit_customer.has_key(col):
                edit_customer[col] = getattr(customer_obj, col)
        if kw.has_key('actions'):
            if kw['actions'].has_key('save'):
                validate = form.Customer()
                try:
                    data = validate.to_python(edit_customer)
                    tables.session.begin()
                    for val in self.iterator_customer_editable:
                        setattr(customer_obj, val, kw['edit_customer'][val])

                    tables.session.commit()
                    raise redirect(url('show',id=id))
                except Invalid, e:
                    errors = e.unpack_errors()

        return dict(this=self,
                    customer = customer_obj,
                    errors = errors,
                    edit_customer = edit_customer,
                    release = self.release,
                    mapper_customer=self.mapper_customer,
                    iterator_customer_editable=self.iterator_customer_editable
                    )